#ifdef LINUX

#include "Network/UDPClient.h"

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>

CUDPClient::CUDPClient()
{
    //create a new udp socket
    PlatformSocket = new int();
    *(int*)PlatformSocket = socket(AF_INET, SOCK_DGRAM, 0);
    assert(*(int*)PlatformSocket != 0);

    //set socket to non-blocking
    int Flags = fcntl(*(int*)PlatformSocket, F_GETFL, 0);
    fcntl(*(int*)PlatformSocket, F_SETFL, Flags | O_NONBLOCK);

    // //get max sendable message size
    // {
    //     int MaxSize;
    //     socklen_t SizeSize;
    //     getsockopt(*(int*)PlatformSocket, SOL_SOCKET, SO_SNDBUF, (void *)&MaxSize, &SizeSize);
    //     MaxSendableMessageSize = MaxSize;
    // }

}

CUDPClient::~CUDPClient()
{
    close(*(int*)PlatformSocket);
    delete (int*)PlatformSocket;
}


void CUDPClient::Send(const TVector<uint8_t>& Data,const SIPAddress & IP, uint16_t Port)
{   
    //assert(Data.Num() <= MaxSendableMessageSize);

    sockaddr_in ServerAddress;
    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_port = htons(Port);
    CString8 IPStr = IP.ToString().ToUtf8String();
    ServerAddress.sin_addr.s_addr = inet_addr(IPStr.CStr());

    sendto(*(int*)PlatformSocket, Data.Data(), Data.Num(), 0, (sockaddr *)&ServerAddress, sizeof(ServerAddress));

}

#endif